package cn.jdemo.juc.jvolatile;

import java.util.concurrent.TimeUnit;

public class Demo01 {

    private int a=0;
    private volatile boolean flag = false;
    public void method1(){
        a = 2;
        flag = true;
    }
    public void method2(){
        if (flag){
            System.out.println(a);
        }else{
            System.out.println("flag = false,a = " + a);
        }
    }

    /**
     * 输出内容:
     * flag = false,a = 0
     * flag = false,a = 0
     * 2
     */
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            Demo01 demo01 = new Demo01();
            Thread thread1 = new Thread(() -> {
                demo01.method1();
            });

            System.out.println("-------------------------------------");
            Thread thread2 = new Thread(() -> {
                demo01.method2();
            });
            thread1.start();
            thread2.start();
        }

    }

}
